package com.glqiang.service.impl;

import com.glqiang.domain.entity.User;
import com.glqiang.exception.CustomException;
import com.glqiang.security.CustomUserDetails;
import com.glqiang.service.CustomUserDetailsService;
import com.glqiang.service.PermissionService;
import com.glqiang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author glqiang
 * @date 2022/11/21 02:10
 */
@Service("customUserDetailsService")
public class CustomUserDetailsServiceImpl implements CustomUserDetailsService, UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查找用户
        User user = userService.getByUsername(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<String> perms = permissionService.listPermissionByUserId(user.getId());
        // List<String> perms = Collections.singletonList("test");
        return new CustomUserDetails(user, perms);
    }

    @Override
    public UserDetails loadUserByPhone(String phone) {
        User user = userService.getByPhone(phone);
        if (Objects.isNull(user)) {
            throw new CustomException("手机号未注册");
        }
        // List<String> perms = menuService.selectPermsByUserId(user.getId());
        List<String> perms = Collections.singletonList("test");
        return new CustomUserDetails(user, perms);
    }
}
